import base from './util/base';
import WfForm_Public from './util/public/interface';
import * as rightBtn from './util/rightBtn';
import { getAntd,getLabel } from './util/convert';
import * as _ from './util/public/common';
import * as GlobalUtil from './util/public/globalUtil';
import * as SubmitUtil from './util/submit';
import * as Util from './util/formUtil';
import { convertSpecialChar } from './util/signUtil';
import { switchFormTab,reloadRequestPage,reloadListPage } from './util/formUtil';
import CellType from './components/layout/CellType';

export const WfForm_PC = {
    showMessage: function(msg, type=1, duration=1.5){
        const message = window.antd.message;
        if(type === 1)      //警告
            message.warning(msg, duration);
        else if(type === 2)     //错误
            message.error(msg, duration);
        else if(type === 3)     //成功
            message.success(msg, duration);
        else    //普通信息
            message.info(msg, duration);
    },
    showConfirm: function(content, okEvent, cancelEvent, otherInfo={}){
        const { Modal } = getAntd();
        Modal.confirm({
            title: otherInfo.title || getLabel(131329,'信息确认'),
            content: React.createElement("div", {dangerouslySetInnerHTML:{__html:content}}),
            okText: otherInfo.okText || getLabel(826,'确定'),
            cancelText: otherInfo.cancelText || getLabel(201,'取消'),
            onOk() {
                typeof okEvent === "function" && okEvent();
            },
            onCancel() {
                typeof cancelEvent === "function" && cancelEvent();
            },
        });
    },
    getSignRemark: function(){
        return  window.CK_REF ? window.CK_REF.remark.getEditor().getData() : "";
    },
    /**
     * 设置签字意见
     * @param {html} 要插入的内容
     * @param {position} 要插入的位置
     * @param {isClear} 默认为false替换意见内容，true追加意见内容
     * @param {callback} 插入成功后的回调函数
     */
    setSignRemark: function(html, isClear=true, isAfter=true, callback){
        const { markInfo,controlVariableMap } = base.globalStore;
        const { use_textarea_signinput } = markInfo;
        //不展开签字意见框可能会设置不生效，ck需要先初始化
        controlVariableMap("isShowSignInput",true);
        if(use_textarea_signinput == 1){
            let value = window.CK_REF ? window.CK_REF.remark.getEditor().getData() : "";
            value =  convertSpecialChar(value);
            value = isClear ? html : (isAfter ? (value + html) : (html + value));
            window.CK_REF.remark.setState({value})
            if(typeof callback==="function"){
                callback();
            }
        }else{
            window.CK_REF.remark.insertHTML(html, isAfter?"last":"first" , isClear, callback);
        }
    },
    reloadPage: function(params={}){
        const { requestid } = base.globalStore.commonParam;
        const newParams = {...{requestid}, ...params};
        reloadRequestPage(newParams);
    },
    reloadListPage: reloadListPage,
    downLoadFile: function(fileid){
        const { commonParam } = base.globalStore;
        const { requestid,authStr,authSignatureStr,f_weaver_belongto_userid,f_weaver_belongto_usertype } = commonParam;
        let url = "/weaver/weaver.file.FileDownload?fileid="+fileid+"&download=1"+"&fromrequest=1";
        url += `&requestid=${requestid}&authStr=${authStr}&authSignatureStr=${authSignatureStr}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}`;
        const ua = window.navigator.userAgent;
        if (Number(ua.replace(/^.*Chrome\/([\d]+).*$/, "$1")) >= 73){
            window.open(url);
        }else{
            jQuery("iframe#WfFormFileDownload").attr("src","about:blank").attr("src", `${url}&random=${new Date().getTime()}`);
        }
    },
    changeOdocConfig:function(info){
        base.layoutStore.setOdocInfo(info);
    },
    switchTab:function(key){
        switchFormTab(key);
    },
    doSave: function(){
        this.doRightBtnEvent("BTN_WFSAVE");
    },
    doSubmit: function(needwfback="1"){
        return SubmitUtil.doSubmitForm({actiontype:"requestOperation", src:"submit", needwfback:needwfback});
    },
    doIntervenor: function(){
        this.doRightBtnEvent("BTN_DOINTERVENOR");
    },
    doIntervenor4AutoTest : function() {
        rightBtn.doIntervenor();
    },
    doRightBtnEvent: function(arg1){
        try{
            const rightMenu = mobx.toJS(base.globalStore.rightMenu.rightMenus);
            let btnObj;
            rightMenu && rightMenu.map(item =>{
                if(typeof arg1 === "string" && arg1 === item.type)
                    btnObj = item;
                else if(typeof arg1 === "object" && arg1.type === item.type && arg1.menuFun === item.menuFun)
                    btnObj = item;
            });
            if(btnObj !== null){
                GlobalUtil.executeRightBtnClick(btnObj,rightBtn);
            }
        }catch(e){
        }
    },
    rightBtn: rightBtn,
    recordNewDocid : function(docid){//记录流程新建的文档id
        const { secLevelInfo = {}, setSecLevelInfo,changeSubmitParam } = base.globalStore;
        let { newDocid } = secLevelInfo;
        if(!newDocid || newDocid == "") {
            newDocid = docid;
        } else {
            newDocid += "," + docid;
        }
        setSecLevelInfo({newDocid : newDocid});
        changeSubmitParam({secNewDocid : newDocid});
    },
    generateFieldContentComp: function(fieldMark){
        const index = fieldMark.indexOf("_");
        const fieldid = index>-1 ? fieldMark.substring(5, index) : fieldMark.substring(5);
        const rowIndex = index>-1 ? fieldMark.substring(index+1) : -1;
        const fieldInfo = WfForm_Public.getFieldInfo(fieldid);
        const symbol = fieldInfo.tableMark || "";
        if(symbol !== ""){
            const detailProps = symbol.indexOf("detail") > -1 ? {rowIndex} : {};
            const cellObj = {id:"0,0", etype:"3", field:fieldid};
            return <CellType ecId={`${this && this.props && this.props.ecId || ''}_CellType@bpd2lq`} symbol={symbol} cellObj={cellObj} detailProps={detailProps} />
        }
        return <span>Field Not Exist</span>;
    },
    appendSubmitParam: function(obj={}){
        _.forIn(obj, (v,k) =>{
            if(_.indexOf(GlobalUtil.importantParamRange, k) > -1)
                delete obj[k];
        });
        base.globalStore.changeSubmitParam(obj);
    },
    getFirstRequiredEmptyField: function(){
        return SubmitUtil.verifyRequiredEmptyField();
    },
    verifyFormRequired: function(mustAddDetail=true, fieldRequired=true){
        let flag = true;
        //校验并提示，必须新增空明细
        if(mustAddDetail){
            flag = SubmitUtil.verifyMustAddDetail();
        }
        //校验并提升，第一个必填字段
        if(fieldRequired && flag){
            const emptyField = this.getFirstRequiredEmptyField();
            if (emptyField !== "") {
                flag = false;
                window.setTimeout(()=>{
                    Util.showPrompt(emptyField, 1);     //明细可能需要切页，延时提示
                },50);
            }
        }
        return flag;
    },
	closeRequestPage:function(requestid){
        Util.closeRequestPage(false, { requestid });
    }
}

const WfForm = {...WfForm_Public, ...WfForm_PC};

window.WfForm = WfForm;
window.wfform = WfForm;

/**
 * 重写E8浏览按钮赋值的函数
 * @param fieldMark  字段标示
 * @param isMustInput 无效参数
 * @param data 修改的数据，JSON含id及name
 * @param _options 修改方式，替换/追加值
 */
window._writeBackData = function(fieldMark, isMustInput, data, _options){
    try{
        if(typeof data !== "object")
            return;
        const _id = data.id || "";
        const _name = data.name || "";
        const options = jQuery.extend({replace:false,isSingle:true}, _options);
        let value = "";
        let specialobj = new Array();
        if(options.isSingle || options.replace){    //替换值
            value = _id;
            if(value !== "")
                specialobj.push({id:_id, name:_name});
        }else{  //追加值
            if(_id === "" || _name === "")
                return;
            let curBrowValue = WfForm.getFieldValueObj(fieldMark) || {};
            value = (curBrowValue.value || "") + "," + _id;
            specialobj = (curBrowValue.specialobj || new Array()).concat([{id:_id, name:_name}]);
        }
        WfForm.changeFieldValue(fieldMark, {value:value, specialobj:specialobj});
    }catch(e){
        if(window.console)  console.log("_writeBackData Exception:"+e);
    }
}